
import React, { useState, useEffect } from 'react';
import './index.less';
import { address } from '@/util/address';
import If from '@/compontent/comm/If';

interface Ioption {
  label: string;
  value: string;
  id: string;
  children?: Array<Ioption>;
}
interface Iprops {
  defaultValue: Array<string>;
  onChange: Function;
}
// 函数防抖处理-输入
let lastTime: any = null;
let timer: any = null;
let outside: boolean = false;
const Cascader = (props: Iprops) => {
  const { defaultValue, onChange } = props;
  const [visible, setVisible] = useState<boolean>(false); // 选项面板-显示
  const [option, setOption] = useState<Array<Ioption>>(address); //选项列表-全部
  const [list, setList] = useState<Array<Ioption>>(address); //选项列表-当前显示
  const [checked, setChecked] = useState<string>(''); //选中的值
  const [search, setSearch] = useState<string>(''); //搜索的值
  const [inputValue, setInputValue] = useState<string>(''); //输入框值
  const [placeholder, setPlaceholder] = useState<string>(''); //输入框显示提示
  const [checkItem, setCheckItem] = useState<Array<Ioption>>([]); //选中的对象集合
  const [checkValue, setCheckValue] = useState<Array<string>>([]); //选中的id
  const [childrenList, setChildren] = useState<Array<Array<Ioption>>>([]); // 需要渲染的子集

  // 防抖
  function debounce(fn: Function, wait: number) {
    let now = +new Date();
    if (lastTime - now < wait) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn();
      lastTime = +new Date();
    }, wait);
  }
  // 进入搜索界面
  function getFcous() {
    setInputValue(search);
  }
  // 输入搜索关键字
  function inputValueFn(e) {
    let val = e.target.value;
    setInputValue(val);
    setSearch(val);
    debounce(() => {
      searchFn(val);
    }, 500);
  }
  // 清理输入框
  function clearFn() {
    if (search === '') {
      setCheckItem([]);
      setInputValue('');
    } else {
      setSearch('');
      setInputValue(checked);
      setList(option);
    }
  }
  //click 选中事件
  function optionClick(item: Ioption, index: number) {
    checkItem[index] = { label: item.label, value: item.label, id: item.id };
    let newCheckItem = checkItem.filter((item, flIndex) => {
      return flIndex <= index;
    });
    setCheckItem([...newCheckItem]);
    // 有子集
    if (item.children != undefined && item.children.length > 0) {
      if (index == 0) {
        // 重置父级
        setChildren([item.children]);
      } else {
        // 替换子集
        let arr = childrenList;
        arr[index] = item.children;
        setChildren([...arr]);
      }
    } else {
      //无子集
      setSearch('');
    }
  }
  // 本地模糊搜索
  function searchFn(value: string) {
    let arr = option.filter(item => {
      return item.label.includes(value);
    });
    setChildren([]);
    setList([...arr]);
  }
  // 点击空白判断
  function onSpaceFn() {
    if (outside) {
      outside = false;
    } else {
      setVisible(false);
    }
  }
  // 点击输入框
  function inputClick() {
    if (!visible) setVisible(true);
  }
  // 默认值定位
  function defaultValueFn(value: string, arr: Array<Ioption>) {
    for (let i = 0; i < arr.length; i++) {
      if (value == arr[i].value) {
        let param = {
          label: arr[i].label,
          value: arr[i].value,
          id: arr[i].id
        };
        childrenList.push(arr[i].children || []);
        setChildren([...childrenList]);
        checkItem.push(param);
        setCheckItem([...checkItem]);
        return arr[i].children;
      }
    }
  }
  //render
  function renderOption() {
    if (list.length === 0) {
      return <div className="ui-cascader-none">暂无数据~</div>;
    } else
      return list.map((item, index) => {
        return (
          <div
            onClick={optionClick.bind(this, item, 0)}
            key={index}
            className={`ui-cascader-option ${checkValue[0] == item.value ? 'ui-cascader-checked' : ''}`}
          >
            <span className="ui-cascader-option-label">{item.label}</span>
            <If show={item.children != undefined && item.children.length > 0}>
              <i className="iconfont icon-youbian"></i>
            </If>
          </div>
        );
      });
  }
  // render item
  function renderItem() {
    return childrenList.map((item, index) => {
      return (
        <div key={index} className="ui-cascader-children">
          {item.map((It, Id) => {
            return (
              <div
                onClick={optionClick.bind(this, It, index + 1)}
                key={Id}
                className={`ui-cascader-option ${checkValue[index + 1] == It.value ? 'ui-cascader-checked' : ''}`}
              >
                <span className="ui-cascader-option-label">{It.label}</span>
                <If show={It.children != undefined && It.children.length > 0}>
                  <i className="iconfont icon-youbian"></i>
                </If>
              </div>
            );
          })}
        </div>
      );
    });
  }
  // 设置默认值
  useEffect(() => {
    if (!defaultValue || defaultValue.length == 0) return;
    let result = defaultValue.filter((item, index) => {
      return item !== checkValue[index];
    });
    if (result.length != 0) {
      let optionList: any = [...option];
      for (let i = 0; i < defaultValue.length; i++) {
        optionList = defaultValueFn(defaultValue[i], optionList);
      }
    }
  }, [defaultValue]);
  useEffect(() => {
    let label = '';
    let len = checkItem.length;
    let idList: Array<string> = [];
    for (let i = 0; i < len; i++) {
      label = `${label}${i !== 0 ? '-' : ''}${checkItem[i].label}`;
      idList.push(checkItem[i].value);
    }
    setCheckValue(idList);
    setChecked(label);
  }, [checkItem]);
  useEffect(() => {
    setPlaceholder(checked == '' ? '请选择' : checked);
    onChange(checkValue);
    setInputValue(checked);
  }, [checked]);
  useEffect(() => {
    if (!visible) setInputValue(checked);
  }, [visible]);
  useEffect(() => {
    window.addEventListener('mouseup', onSpaceFn);
    return () => {
      window.removeEventListener('mouseup', onSpaceFn);
    };
  }, []);

  return (
    <div
      className="ui-cascader"
      onMouseDown={() => {
        outside = true;
      }}
    >
      <div className={`ui-cascader-reveal ${visible ? 'ui-cascader-focus' : ''}`} onClick={inputClick.bind(this)}>
        <input
          onInput={inputValueFn.bind(this)}
          onFocus={getFcous.bind(this)}
          value={inputValue}
          className="ui-cascader-input"
          placeholder={placeholder}
          type="text"
        />
        <i onClick={clearFn.bind(this)} className={`iconfont icon-close-circle ${inputValue == '' ? 'close-hidden' : ''}`}></i>
        <span className="ui-cascader-reveal-icon">
          <i className={`iconfont icon-${visible ? 'fangdajing' : 'xiabian'} `} onClick={setVisible.bind(this, !visible)}></i>
        </span>
      </div>
      <div className={`ui-cascader-panel ${visible ? '' : 'ui-cascader-hidden'}`}>
        <div className="ui-cascader-panel-scroll">{renderOption()}</div>
        {renderItem()}
      </div>
    </div>
  );
};

export default Cascader;
